<?php
// +----------------------------------------------------------------------
// | UCToo [ Universal Convergence Technology ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014-2018 http://uctoo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Patrick <contact@uctoo.com>
// +----------------------------------------------------------------------

namespace app\mpopen\controller;

use app\common\controller\Backend;
use app\common\model\User;
use app\admin\model\Admin;
use app\admin\model\AdminLog;
use app\common\model\Order;
use com\TPWechatOpen;
use com\wxpay\database\WxPayUnifiedOrder;
use com\wxpay\JsApiPay;
use com\wxpay\NativePay;
use com\wxpay\WxPayApi;
use com\wxpay\WxPayConfig;
use app\common\model\WechatApplet;
use app\common\controller\Frontend;
use app\mpopen\controller\PayNotifyCallBack;

/**
 * 统一支付收银台
 */
class Unipay extends Backend {

    protected $noNeedLogin = ['notify','wxpayjsapi','wxpayqrcode','wxpayqc'];

    public function index()
    {
        return $this->view->fetch();
    }

    /**
     * 微信支付收银台方法
     * 在公众号后台mp.weixin.qq.com支付授权目录配置https://www.uctoo.com/mpopen/unipay/wxjsapipay/mp_id/公众号表mp_id字段/order_id/
     * 需要微信支付功能的地方带上order表的id参数跳转到此地址即可。
     * @param string $order_id  Order表order_id 字段
     * @return mixed
     */
    public function wxpayjsapi()
    {
        $order_id = input('order_id');
        $mp_id = input('mp_id');
        $orderData = Order::get(['order_id'=>$order_id]);
        trace($orderData,'order');
        $this->assign ( 'mp_id', $mp_id );
        $appinfo = WechatApplet::get(['appletid' => $mp_id]);//获取公众号信息
        $this->assign ( 'appinfo', $appinfo );
        $openid = $orderData['buyer_openid'];  //TODO：下单人的openid不一定就是扫码支付人的openid，后续通过扫码时的静默授权获取支付人openid
        trace('get_index','info');
        trace($openid,'info');
        $mid = $orderData['mid'];
        if($mid === false){
            $this->error('只可在微信中访问');
        }
        $cfg = array(
            'APPID'     => $appinfo['appid'],
            'MCHID'     => $appinfo['mchid'],
            'KEY'       => $appinfo['mchkey'],
            'APPSECRET' => $appinfo['appsecret'],
            'NOTIFY_URL' => $appinfo['notify_url'],
        );
        WxPayConfig::setConfig($cfg);

        if (isset($order_id) && $order_id != 0) {
            //获取用户openid
            $tools = new JsApiPay();
            trace($tools,'JsApiPay');
            //统一下单
            $input = new WxPayUnifiedOrder();
            $input->setBody($orderData->product_name);
            $input->setAttach($orderData->product_sku);
            $input->setOutTradeNo($orderData->order_id);  //建议默认的预支付交易单商户订单号由date("YmdHis").'_'.order_id组成
            $input->setTotalFee($orderData->order_total_price);
            $input->setTimeStart(date("YmdHis"));
            $input->setTimeExpire(date("YmdHis", time() + 600));
            $input->setGoodsTag("Reward");
            $input->setNotifyUrl($appinfo['notify_url']);
            trace($input,'notify_url');
            $input->setTradeType("JSAPI");
            $input->setOpenid($openid);
            $order = WxPayApi::unifiedOrder($input);


            $jsApiParameters = $tools->getJsApiParameters($order);
            trace($order,'order');
            trace($jsApiParameters,'jsApiParameters');
            trace($orderData,'orderData');
            $this->assign('order', $order);
            $this->assign('orderData', $orderData);
            $this->assign('jsApiParameters', $jsApiParameters);
            return $this->fetch();
        }
    }

    /**
     * 使用微信支付SDK生成支付用的二维码
     * 需要显示扫码支付二维码的地方带上order表的order_id参数 <img src="{:url('mpopen/unipay/wxpayqrcode',['mp_id'=>$mp_id,'order_id'=>$order_id])}">
     * 用户十分钟未支付，则微信支付预支付订单过期需
     * @param $order_id
     */
    public function wxpayqrcode()
    {
        $order_id = input('order_id');
        $mp_id = input('mp_id');
        $orderData = Order::get(['order_id'=>$order_id]);
        trace($orderData,'order');
        $this->assign ( 'mp_id', $mp_id );
        $appinfo = WechatApplet::get(['appletid' => $mp_id]);//获取公众号信息
        $this->assign ( 'appinfo', $appinfo );
        $openid = $orderData['buyer_openid'];  //TODO：下单人的openid不一定就是扫码支付人的openid，后续通过扫码时的静默授权获取支付人openid
        trace('get_index','info');
        trace($openid,'info');
        $mid = $orderData['mid'];
        if($mid === false){
            $this->error('只可在微信中访问');
        }
        $notify_url = url('mpopen/unipay/notify','','',true);
        $cfg = array(
            'APPID'     => $appinfo['appid'],
            'MCHID'     => $appinfo['mchid'],
            'KEY'       => $appinfo['mchkey'],
            'APPSECRET' => $appinfo['appsecret'],
            'NOTIFY_URL' => $notify_url,
        );
        WxPayConfig::setConfig($cfg);
        //判断是否已经存在订单 url，如果已经存在且未超过2小时就使用旧的，否则生成新的
        $interval = time() - $orderData->update_time;
        trace($interval,'interval');
        if (isset($orderData->pay_url) && $orderData->pay_url != '' && $interval < 600) {
            $url = $orderData->pay_url;
            trace($url,'pay_url111');
        } else {
            $notify = new NativePay();
            $input = new WxPayUnifiedOrder();
            $input->setBody($orderData->product_name);
            $input->setAttach($orderData->product_sku);
            $input->setOutTradeNo($orderData->order_id);
            $input->setTotalFee($orderData->order_total_price);
            $input->setTimeStart(date("YmdHis"));
            $input->setTimeExpire(date("YmdHis", time() + 600));
            $input->setGoodsTag("QRCode");
            $input->setNotifyUrl($notify_url);

            $input->setTradeType("NATIVE");
            $input->setProductId($orderData->product_id);
            $result = $notify->getPayUrl($input);
            trace($result,'result');
            $url = $result["code_url"];
            trace($url,'code_url');
            //保存订单标识
            $orderData->pay_url = $url;
            $orderData->save();
        }

        //生成二维码
        return getUrlQRCode($url);
    }
    /**
     * 微信支付二维码收银台方法
     * 需要微信扫码支付功能的地方带上order表的id参数跳转到此地址即可。https://www.uctoo.com/mpopen/unipay/wxpayqc/mp_id/公众号表mp_id字段/order_id/
     * @return mixed
     */
    public function wxpayqc()
    {
        $mp_id = input('mp_id');
        $order_id = input('order_id');
        $orderData = Order::get(['order_id'=>$order_id]);
        if (!isset($orderData)) $this->error('查询不到正确的订单信息');
        $this->view->assign('orderData', $orderData);
        $this->view->assign('mp_id', $mp_id);
        $this->view->assign('order_id', $order_id);
        return $this->view->fetch();
    }

    /**
     * 异步接收订单返回信息，订单成功付款后，处理订单状态并批量生成用户的二维码
     * https://www.uctoo.com/mpopen/unipay/notify
     * @param int $id 订单编号
     */
    public function notify(){
        $rsv_data = request()->getInput();
        $result   = xmlToArray($rsv_data);
        trace($result,'notifyresult');

        $map["appid"] = $result["appid"];
        $info = WechatApplet::get(['appid' => $result["appid"]]);//获取公众号信息
        $mp_id = $info['appletid'];
        $notify_url = url('mpopen/unipay/notify','','',true);
        addWeixinLog ( $rsv_data, '',$mp_id, 0,$result['appid'],$result['openid'],'wxpay_notify');
        //获取公众号信息，jsApiPay初始化参数
        $cfg = array(
            'APPID'      => $info['appid'],
            'MCHID'      => $info['mchid'],
            'KEY'        => $info['mchkey'],
            'APPSECRET'  => $info['appsecret'],
            'NOTIFY_URL' => $notify_url,
        );
        WxPayConfig::setConfig($cfg);

        //回复公众平台支付结果
        $notify = new PayNotifyCallBack();
        $notify->Handle(false);
    }
}
